package P7.T07;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class T07 {
    public static void main(String[] args) {
        Monitor m=new Monitor();
        Consumer[] cs=new Consumer[20];
        Producer[] ps=new Producer[20];
        for(int i=0;i<20;i++){
            cs[i]=new Consumer(m);
            ps[i]=new Producer(m);
        }
        for(int i=0;i<20;i++){
            cs[i].start();
            ps[i].start();
        }
    }
}
class Consumer extends Thread{

    Monitor m=null;
    public Consumer(Monitor m){
        this.m=m;
    }
    @Override
    public void run() {
        try {
            m.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
class Producer extends  Thread{

    Monitor m=null;
    public Producer(Monitor m){
        this.m=m;
    }
    @Override
    public void run() {
        try {
            m.put();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
class Monitor{

    private final int MaxShoes=20;
    private Condition op,oc;
    private ReentrantLock lock;
    int shoes=0;
    public Monitor(){
        lock=new ReentrantLock();
        op=lock.newCondition();
        oc=lock.newCondition();
    }
    public void put() throws InterruptedException {
        lock.lock();
        if(shoes==MaxShoes){
            op.await();
        }
        shoes++;
        System.out.println("生产了一双，现在已经生产了"+shoes+"双鞋子");
        oc.signal();
        lock.unlock();
    }

    public void get() throws InterruptedException {
        lock.lock();
        if(shoes==0){
            oc.await();
        }
        shoes--;
        System.out.println("取走了一双，现在还剩"+shoes+"双鞋子");
        op.signal();
        lock.unlock();
    }
}